<?php
namespace app\common\energyApi;



use Jrk\Redis;

class Common
{
    public function __construct(){

        $this->site_url = "http://120.55.104.220:8780/emcp/";  //请求地址 （需要拼接上版本号）
        $this->version = "v1/"; //版本号
        $this->end_url = $this->site_url.$this->version;
        $this->operatorId = "348375758"; //商户编号
        $this->operatorSecret = "d8pTAwCXx9RN6ZWw"; //商户密钥
        $this->dataSecret = "5DzfBaNAb0X4jQ75"; //消息密钥
        $this->dataSecretIV = "dIquEfJqGunNwjRj"; //消息密钥初始化向量
        $this->sigSecret = "zDDQSIIKueyff9Rm"; //签名密钥
        $this->redis = new Redis();
    }
    //返回数据（data）解密并加以判断获取

    //数据加密
    public function encrypt($input){
        return base64_encode(@openssl_encrypt($input, 'AES-128-CBC',$this->dataSecret , OPENSSL_RAW_DATA,$this->dataSecretIV));
    }

    // 数据解密
    public function decrypt($input)
    {
        return openssl_decrypt(base64_decode($input), 'AES-128-CBC', $this->dataSecret, OPENSSL_RAW_DATA, $this->dataSecretIV);
    }

    /* 签名  sign
    * @param String $data 预加密数据
    * @param String $key  密钥
    * @return String
    */
    public function hmac($data)
    {
        $key = $this->sigSecret;
        $data = $this->operatorId.$data.$this->getOrderTime().'0001';
        if (function_exists('hash_hmac')) {
            return hash_hmac('md5', $data, $key);
        }
        $key = (strlen($key) > 64) ? pack('H32', 'md5') : str_pad($key, 64, chr(0));
        $ipad = substr($key,0, 64) ^ str_repeat(chr(0x36), 64);
        $opad = substr($key,0, 64) ^ str_repeat(chr(0x5C), 64);
        return md5($opad.pack('H32', md5($ipad.$data)));
    }



    //php 获取14位 yyyyMMddHHmmss 格式时间戳
    public function getOrderTime()
    {
        list($usec, $sec) = explode(" ", microtime());
        $cn_time=date('YmdHis', time()).round($usec*1000);
        return  substr($cn_time,0,strlen($cn_time)-2);
    }

    //仅限于水电管理api使用
    public function api_post($site,$data = "",$token = ""){
        $curl = curl_init();
        $url = $this->end_url.$site;
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>isset($data)?$data:'',
            CURLOPT_HTTPHEADER => array(
                'authorization: '.$token,
                'Content-Type: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
}